<template>
  <div class="p-t">
    <table class="el-table" id="tableId">
      <thead>
        <tr>
          <th class="th-min textc" v-for="(item, index) in specData" :key="index">
            {{ item.specsName }}
          </th>
          <template v-for="item in thList">
            <th class="textc" :class="{ pic: item.form == 'pic' }" :key="item.name">
              {{ item.name }}
            </th>
          </template>
          <th class="textc" style="width:70px">状态</th>
        </tr>
      </thead>
      <tbody>
        <tr :key="index" v-for="(item, index) in SKUNums" class="tr-tbody">
          <template v-for="(n, specIndex) in specData.length">
            <td class="textc" v-if="showTd(specIndex, index)" :key="n" :rowspan="countSum(n)">
              {{ getSpecAttr(specIndex, index) }}
            </td>
          </template>
          <template v-for="item in thList">
            <td class="textc" :class="{ pic: item.form == 'pic' }" :key="item.form" @click="handleUpload(index)">
              <imageUpload v-if="item.form == 'pic'" v-model="specTable[index].imgCoverUrl" />
              <div v-else>
                <el-input v-if="item.form == 'stockNumber'" size="small" type="text" class="input-center"
                  :class="{ 'input-width': item.form === 'stockNumber' }" :disabled="!specTable[index].isUse"
                  :value="specTable[index][item.form]" v-model="specTable[index][item.form]"
                  @blur="item.form === 'stockNumber' ? handleNo(index) : ''" onkeyup="value=value.replace(/[^\d]/g,'')">
                </el-input>
                <el-input v-else-if="item.form == 'skuNo'" size="small" type="text" class="input-center"
                  :class="{ 'input-width': item.form === 'skuNo' }" :disabled="!specTable[index].isUse"
                  :value="specTable[index][item.form]" v-model="specTable[index][item.form]" maxlength="20"></el-input>
                <el-input required v-else size="small" type="text" class="input-center"
                  :class="{ 'input-width': item.form === 'stockNumber' }" :disabled="!specTable[index].isUse"
                  :value="specTable[index][item.form]" v-model="specTable[index][item.form]"
                  @blur="item.form === 'stockNumber' ? handleNo(index) : unInput(specTable[index][item.form],index,item.form) "
                  @keyup.native="specTable[index][item.form] = oninput(specTable[index][item.form],2)"></el-input>
              </div>
            </td>
          </template>
          <td v-if="orUse" class="textc">
            <el-switch v-model="specTable[index].isUse"></el-switch>
          </td>
        </tr>
        <tr>
          <td colspan="8" class="wh-foot">
            <span class="label">批量设置：</span>
            <template v-if="isSetListShow">
              <template v-for="item in thList">
                <el-button :key="item.name" size="mini" v-if="item.type" @click="openBatch(item.type)">{{ item.name }}
                </el-button>
              </template>
            </template>
            <template v-else>
              <div class="inline-block" v-for="item in thList" :key="item.name">
                <imageUpload v-if="
                    item.type && item.type === 'pic' && currentType === 'pic'
                  " v-model="specTable[index].imgCoverUrl" />
                <el-input v-else-if="item.type && currentType === item.type" size="mini" style="width: 200px"
                  type="text" :key="item.name" v-model="batchValue" :placeholder="item.name"
                  @keyup.native.enter="setBatch"></el-input>
              </div>
              <el-button style="margin-left: 20px" type="primary" size="mini" @click="setBatch">
                <i class="set-btn blue el-icon-check"></i>
              </el-button>
              <el-button type="danger" size="mini" @click="cancelBatch">
                <i class="set-btn blue el-icon-close"></i>
              </el-button>
            </template>
          </td>
        </tr>
      </tbody>
    </table>
    <el-dialog :visible.sync="visible">
      <img width="100%" :src="previewUrl" />
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import specMixins from "./mixins";
  import upload from "@/components/sku/upload";
  import ImageUpload from "@/components/ImageUpload";

  export default {
    components: {
      ImageUpload,
    },
    props: {
      orUse: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        isSetListShow: true, // 批量设置状态
        currentType: "", // 批量设置绑定的类型
        batchValue: "", // 批量设置绑定的值
        previewUrl: "",
        visible: false,
        picIndex: 0,
        urls: "",
        file: [],
      };
    },
    mixins: [specMixins],
    methods: {
      //去掉小数点
      unInput(num, index, item) {
        let str = num + "";
        if (str.indexOf(".") == str.length - 1) {
          this.specTable[index][item] = str.substring(0, str.length - 1);
        }
        let a1 = this.specTable[index]["costPrice"];
        let a2 = this.specTable[index]["skuRetailPrice"];
        if (a1 != null && a1 != "" && a2 != null && a2 != "") {
          if (a1 > a2) {
            this.$message.error("供货价要小于零售价！");
          }
        }

      },
      oninput(num, limit) {

        let str = num;
        let len1 = str.substr(0, 1);
        let len2 = str.substr(1, 1);
        //如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 == 0 && len2 != ".") {
          str = str.substr(1, 1);
        }
        //第一位不能是.
        if (len1 == ".") {
          str = "";
        }
        //限制只能输入一个小数点
        if (str.indexOf(".") != -1) {
          let str_ = str.substr(str.indexOf(".") + 1);
          if (str_.indexOf(".") != -1) {
            str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
          }
        }
        //正则替换
        str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
        if (limit / 1 === 1) {
          str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, "$1"); // 小数点后只能输 1 位
        } else {
          str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, "$1"); // 小数点后只能输 2 位

        }
        return str;
      },
      // 是否显示td
      showTd(specIndex, index) {
        if (!this.specData[specIndex]) {
          return false;
        } else if (index % this.countSum(specIndex + 1) === 0) {
          return true;
        } else {
          return false;
        }
      },
      // 编号
      handleNo(index) {
        const value = this.specTable[index].bianhao;
        let isRepet;
        this.specTable.forEach((item, i) => {
          if (item.bianhao === value && i !== index) isRepet = true;
        });
        if (isRepet)
          this.$set(
            this.specTable[index],
            "bianhao",
            this.makeProductNoNotRepet(index)
          );
      },
      openBatch(type) {
        this.currentType = type;
        this.isSetListShow = false;
      },
      // 批量设置
      setBatch() {
        let num = /^[0-9]*[1-9][0-9]*$/;
        let dou = /^\+?(\d*\.\d{2})$/;
        let val = this.batchValue;
        if (this.currentType === "stockNumber") {
          if (!num.test(val)) {
            this.$message({
              type: "warning",
              message: "请输入正确的值"
            });
            return;
          }
        } else {
          let ind = 0;
          if (num.test(val)) {
            ind = ind + 1
          }
          if (dou.test(val)) {
            ind = ind + 1;
          }
          if (ind == 0) {
            this.$message({
              type: "warning",
              message: "请输入正确的值(最多只能输入2位小数)"
            });
            return;
          }
        }

        this.specTable.forEach((item) => {
          // item.picArr.push(this.file)
          // this.$set(item, "imgCoverUrl", this.urls);
          if (item.isUse) item[this.currentType] = val;
        });
        this.cancelBatch();
      },
      cancelBatch() {
        this.specTable.forEach((item) => {
          // this.specTable.urls = ''
          item.picArr = [];
        });
        this.batchValue = "";
        this.currentType = "";
        this.isSetListShow = true;
      },
      makeProductNoNotRepet(index) {
        let No;
        let i = index;
        let isRepet = true;
        while (isRepet) {
          No = this.defaultProductNo + i;
          isRepet = this.isProductNoRepet(No);
          i++;
        }
        return No;
      },
      isProductNoRepet(No) {
        const result = this.specTable.findIndex((item) => {
          return item.bianhao === No;
        });
        return result > -1;
      },
      handleUpload(index) {
        this.picIndex = index;
      },
      uploadSuccessRemove(o) {
        const {
          file,
          fileList,
          urls
        } = o;
        let arr = [];
        fileList.forEach((item) => {
          arr.push(item.response.id);
        });
        const index = this.picIndex;
        this.$set(this.specTable[index], "pic", arr);
        this.$set(this.specTable[index], "picArr", fileList);
        this.$set(this.specTable[index], "imgCoverUrl", urls);
      },
      uploadSuccessRemoveAll(o) {
        const {
          file,
          fileList
        } = o;
        this.urls = o.urls;
        this.file = o.file;
        if (this.urls) {
          this.specTable.forEach((item) => {
            // this.$set(item, "imgCoverUrl", urls);
            item.picArr.push(file);
          });
        }
        // else if(type == "remove") {
        //   this.specTable.forEach((item, index) => {
        //     if(item.picArr.length) {
        //       item.picArr.forEach((im, idx) => {
        //         if(im.uid === file.uid) {
        //           this.specTable[index].pic.splice(idx, 1)
        //           this.specTable[index].picArr.splice(idx, 1)
        //         }
        //       })
        //     }
        //   })
        // }
      },
    },
  };
</script>

<style lang="less" scoped>
  /deep/ .el-upload--picture-card {
    width: 60px;
    height: 60px;
  }

  /deep/ .el-upload {
    width: 60px;
    height: 60px;
    line-height: 60px;
  }

  /deep/ .el-upload-list--picture-card .el-upload-list__item {
    width: 60px;
    height: 60px;
    line-height: 60px;
  }

  /deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 60px;
    height: 60px;
    line-height: 60px;
  }

  /deep/ .avatar {
    width: 60px;
    height: 60px;
  }

  .el-icon-plus {
    font-size: 14px;
  }

  // .p-t {
  //   max-width: 840px;
  //   min-width: 400px;
  // }

  th,
  td {
    text-align: center;
  }

  .wh-foot {
    text-align: left;
  }

  //
  //.input-center {
  //  width: 90px;
  //}
  .el-input {
    width: 125px;
  }

  //.input-width {
  //  width: auto;
  //}

  .el-input__inner {
    text-align: left;
  }

  .el-input__inner {
    text-align: center;
  }

  .inline-block {
    display: inline-block;
    vertical-align: middle;
  }

  // .pic,
  // .pic .pic-box {
  //   display: flex;
  //   justify-content: center;
  //   flex-wrap: wrap;
  // }

  .el-upload-list__item,
  .el-upload {
    width: 62px;
    height: 62px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .el-upload-list--picture-card {
    display: flex;
    flex-wrap: wrap;
  }

  .el-upload-list {
    display: flex;
    align-items: center;
  }

  .el-upload-list {
    padding-top: 8px;
  }

  .pic-disabled {
    pointer-events: none;
    cursor: not-allowed;
  }

  .el-upload--picture-card {
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
  }

  .el-upload-list__item {
    opacity: 0.6;
    background-color: rgba(0, 0, 0, 0.2);
  }

  .el-icon-plus {
    color: #ccc;
  }

  .el-upload-list__item-status-label {
    background-color: #999;
  }

  .el-icon-upload-success {
    opacity: 0.5;
  }

  // .textc {
  //   text-align: center;
  //   padding-left: 3px;
  //   padding-right: 3px;
  // }

  .th-min {
    min-width: 50px;
  }

  table,
  tbody,
  tfoot,
  thead,
  tr,
  th,
  td {
    // border: 1px solid #909399;
    color: #909399;

  }

  // .p-t table {
  //     border-collapse: separate;
  //     border-spacing: 3px
  // }

  .p-t {
    width: 100%;
    height: auto;
    overflow: hidden;
    margin: 10px auto;
  }

  .p-t table {
    width: 100%;
  }

  .p-t table th {
    height: 40px;
    // line-height: 30px;
    background: #F5F7FA;
    font-size: 14px;
    font-weight: normal;
    border-radius: 4px;
    font-weight: bold;
  }

  .wh-foot {
    border: 0;
    font-size: 12px;
  }
</style>
